package com.mine.proxy;

import com.mine.common.Invocation;
import com.mine.common.URL;
import com.mine.loadbalance.LoadBalancer;
import com.mine.protocol.HttpClient;
import com.mine.register.ServerRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @author weixiao
 * @date 2025/3/31 13:31
 */
public class ProxyFactory {

    public static <T> T getProxy(Class interfaceClass) {
        Object proxy = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(),
                        args, method.getParameterTypes());
                // 服务发现
                List<URL> urls = ServerRegister.get(interfaceClass.getName());
                // 负载均衡
                URL url = LoadBalancer.random(urls);
                // 服务容错机制
                Object obj = null;
                try {
                    obj = HttpClient.send(url.getHostname(), url.getPort(), invocation);
                } catch (Exception e) {
                    obj = "服务出错了";
                }
                return obj;
            }
        });
        return (T) proxy;
    }
}
